package com.haojiang.mh.ui.activity

import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.service.ble.BleHandle
import com.haojiang.mh.service.ble.UpdateType
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.utils.MUtil
import kotlinx.android.synthetic.main.activity_update_firmware.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 固件升级进度
 *
 * Created by ZapFive on 2019-05-26.
 *
 * wuzhuang@mirahome.me
 */
class UpdateFirmwareActivity : BaseActivity() {

    private var waitUpdateStartJob: Job? = null //等待升级开始最多3秒

    override fun getLayoutId() = R.layout.activity_update_firmware

    override fun getTitleName() = ""

    override fun initActivity() {
        BleHandle.instance.sendUpdateFirmware()
    }

    override fun initView() {
        startWaitJob(false)
    }

    override fun onDestroy() {
        MUtil.cancelJob(waitUpdateStartJob)
        super.onDestroy()
    }

    override fun onBackClick() {
        //do nothing
    }

    /**
     * 开始等待
     */
    private fun startWaitJob(isFail: Boolean) {
        MUtil.cancelJob(waitUpdateStartJob)
        waitUpdateStartJob = GlobalScope.launch {
            if (isFail) {
                delay(1_500L)
                withContext(Dispatchers.Main) {
                    context.finish()
                }
            } else {
                delay(30_000L)
                withContext(Dispatchers.Main) {
                    showLongToast(getString(R.string.tip_update_fail))
                    delay(1_500L)
                    context.finish()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceicerEvent(event: OneEvent) {
        when (event.type) {
            Const.UPDATE_PROGRESS -> {
                MUtil.cancelJob(waitUpdateStartJob)
                tpv_device_update.setValue(event.getIntValue())
            }
            Const.UPDATE_RESULT -> {
                when (event.getIntValue().toByte()) {
                    UpdateType.UPDATE_SUCCESS.code -> {
                        BleHandle.instance.disConnectDevice()
                        BleHandle.instance.onDeviceDisconnect()
                        redirectWithExtraAndFinish(Const.UPDATE_Firmware_SUCCESS, CommonSuccessActivity::class.java)
                    }
                    UpdateType.UPDATE_FAIL.code -> {
                        showLongToast(getString(R.string.tip_update_fail))
                        startWaitJob(true)
                    }
                }
            }
        }
    }
}